import datetime

from config import BaseConfig
from db.dao import IndustryGrowthListDao, IndustryStockListDao, StockPoolDao, ConceptRankingListDao, ConceptStockListDao
from service.requests.Eastmoney import Eastmoney
from service.stock.common import Extremum, ApplicationUtil, ProfitUtil
from utils.blacklist import StockBlack

industry_blacklist = BaseConfig.CUSTOM_INDUSTRY_BLACK
concept_blacklist = BaseConfig.CUSTOM_CONCEPT_BLACK


def industry_growth_list():
    growth_list = Eastmoney.get_industry_growth_list()
    if growth_list:
        for industryGrowthList in growth_list:
            if not industryGrowthList:
                continue
            interval = getattr(industryGrowthList, 'time_interval')
            if not interval:
                continue
            if interval > '60':
                continue

            IndustryGrowthListDao().saveOrUpdate(industryGrowthList)

            industry_name = getattr(industryGrowthList, 'industry_name')
            if industry_name in industry_blacklist:
                continue

            industry_code = getattr(industryGrowthList, 'industry_code')
            otherStyleTime = getattr(industryGrowthList, 'create_time')
            pctChg = getattr(industryGrowthList, 'pctChg')

            create_stock_pool(industry_code, industry_name, pctChg, interval, otherStyleTime)


def create_stock_pool(industry_code, industry_name, industry_pctChg, time_interval, create_time):
    '''
    过滤股票保存进股票池
    1. 黑名单pass
    2. 股价<7 pass
    3. 股票涨幅负的 pass
    4. 股票涨幅<行业涨幅 pass
    5. 资金净流出的 pass
    :param industry_code: 行业编码
    :param industry_name: 行业名称
    :param industry_pctChg: 行业涨幅榜
    :param time_interval: 时间区间
    :param create_time: 创建时间
    :return:
    '''
    stock_rank_list = Eastmoney.get_stock_rank(industry_code, industry_name, time_interval, create_time)

    if stock_rank_list:
        for stock in stock_rank_list:

            stock_name = getattr(stock, 'stock_name')
            stock_code = getattr(stock, 'stock_code')

            # 在黑名单里的pass
            if StockBlack.checkInBlackList(stock_code=stock_code, stock_name=stock_name):
                continue

            # 最新价格
            now_price = getattr(stock, 'now_price')
            # 价格过滤
            if '-' == now_price:
                break
            if now_price < 7.00:
                continue
            # 涨跌幅
            pctChg = getattr(stock, 'pctChg')

            # 涨幅小于行业涨幅的pass
            if pctChg < 0:
                break
            if pctChg < industry_pctChg:
                break
            # 资金净流入
            main_net_inflow = getattr(stock, 'main_net_inflow')
            # 资金过滤
            if main_net_inflow < 0:
                break

            IndustryStockListDao().saveOrUpdate(stock)


def stock_pool_monitor():
    stock_pool_list = StockPoolDao().findAll()
    ids = []
    if stock_pool_list:
        end_date = datetime.datetime.now().date()
        start_date = end_date + datetime.timedelta(days=-10)

        for stock in stock_pool_list:
            pd_kline = Eastmoney.get_klines(getattr(stock, 'stock_code'))
            if pd_kline.empty:
                continue
            stock_day_str = str(pd_kline.index[-1])
            stock_day_str = stock_day_str.split(' ')[0]
            str2date = datetime.datetime.strptime(stock_day_str, "%Y-%m-%d").date()  # 字符串转化为date形式
            if not (start_date <= str2date <= end_date):
                #     股票最新日期不在区间范围内，说明停牌期间
                continue
            high_date, high_price = Extremum.highest(pd_kline, "close", str(start_date), str(end_date))
            chg_high = ProfitUtil.calculationChg(pd_kline.iloc[-1, 1], high_price)
            if chg_high < -5.00:
                # 近期高点跌超5%，移出股票池
                ids.append(getattr(stock, 'id'))
            chg_today = ProfitUtil.calculationChg(pd_kline.iloc[-1, 1], pd_kline.iloc[-1, 2])
            if chg_today < -2.00:
                # 单日高点跌超2%
                ids.append(getattr(stock, 'id'))
    if ids:
        StockPoolDao().removeStockPoolBatch(ids)


def concept_ranking_list():
    concept_ranking_list = Eastmoney.get_concept_ranking_list()
    if concept_ranking_list:
        for concept in concept_ranking_list:
            if not concept:
                continue

            concept_name = getattr(concept, 'concept_name')
            if concept_name in concept_blacklist:
                continue

            interval = getattr(concept, 'time_interval')
            if not interval:
                continue
            if interval > '60':
                continue

            ConceptRankingListDao().saveOrUpdate(concept)

            concept_code = getattr(concept, 'concept_code')
            otherStyleTime = getattr(concept, 'create_time')
            pctChg = getattr(concept, 'pctChg')

            create_concept_stock_pool(concept_code, concept_name, pctChg, interval, otherStyleTime)


def create_concept_stock_pool(concept_code, concept_name, concept_pctChg, time_interval, create_time):
    '''
    过滤股票保存进股票池
    1. 黑名单pass
    2. 股价<7 pass
    3. 股票涨幅负的 pass
    4. 股票涨幅<行业涨幅 pass
    5. 资金净流出的 pass
    :param industry_code: 行业编码
    :param industry_name: 行业名称
    :param industry_pctChg: 行业涨幅榜
    :param time_interval: 时间区间
    :param create_time: 创建时间
    :return:
    '''
    stock_rank_list = Eastmoney.get_concept_stock_rank(concept_code, concept_name, time_interval, create_time)

    if stock_rank_list:
        for stock in stock_rank_list:

            stock_name = getattr(stock, 'stock_name')
            stock_code = getattr(stock, 'stock_code')

            # 在黑名单里的pass
            if StockBlack.checkInBlackList(stock_code=stock_code, stock_name=stock_name):
                continue

            # 最新价格
            now_price = getattr(stock, 'now_price')
            # 价格过滤
            if '-' == now_price:
                break
            if now_price < 7.00:
                continue
            # 涨跌幅
            pctChg = getattr(stock, 'pctChg')

            # 涨幅小于行业涨幅的pass
            if pctChg < 0:
                break
            if pctChg < concept_pctChg:
                break
            # 资金净流入
            main_net_inflow = getattr(stock, 'main_net_inflow')
            # 资金过滤
            if main_net_inflow < 0:
                break

            ConceptStockListDao().saveOrUpdate(stock)


if __name__ == '__main__':
    concept_ranking_list()
